package com.open.chat.server.handler;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import org.jim.core.ImConst;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.core.cache.redis.RedisCacheManager;
import org.jim.core.config.ImConfig;
import org.jim.core.message.MessageHelper;
import org.jim.core.packets.Group;
import org.jim.core.packets.User;
import org.jim.core.packets.UserStatusType;
import org.jim.server.JimServerAPI;
import org.jim.server.command.handler.extend.utils.SystemNotify;
import org.jim.server.command.handler.extend.utils.SystemNotify.Operation;
import org.jim.server.config.ImServerConfig;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.open.chat.server.common.redis.CommonKey;

/**
 * MQ处理组消息
 * @author admin
 *
 */
public class GroupHelper {
	
	/**
	 * 解散群
	 * @param groupId
	 * @param imChannelContext
	 */
	public static  void  unbind(String currentUserId,String groupId) {
		
		ImServerConfig imServerConfig = ImConfig.Global.get();
		MessageHelper messageHelper = imServerConfig.getMessageHelper();
		
		Group g = messageHelper.getGroupUsers(groupId, UserStatusType.ALL.getNumber());
		
		if(!Objects.isNull(g)  && g.getLeaderId().equals(currentUserId)) {
			
			//删除群组的所有消息
			RedisCacheManager.getCache(ImConst.STORE).remove(ImConst.GROUP+CommonKey.SUFFIX+groupId);
			
			//维护缓存关系
			for(User  user : g.getUsers()) {
				
				JimServerAPI.unbindGroup(user.getUserId(), groupId);
				messageHelper.removeGroupUser(user.getUserId(), groupId);
				//删除群组所有用户的离线消息
				RedisCacheManager.getCache(ImConst.PUSH).remove(ImConst.GROUP+CommonKey.SUFFIX+groupId+CommonKey.SUFFIX+user.getUserId());
				
				JSONObject js = new JSONObject();
				//前端可能用得着
				js.put("groupId", groupId);
				//系统展示 (currentUserId已经不存在,无须通知)
				if(!currentUserId.equals(user.getUserId())) {
					SystemNotify.notifyUser(
							user.getUserId(), user.getNick(), 
							String.format("群(%s)被解散,原因：群主被系统账户删除",g.getName()),Operation.oper_no);
					//通知所有人做业务处理
					SystemNotify.notifyUser(
							user.getUserId(), user.getNick(), 
							String.format("群(%s)被解散,原因：群主被系统账户删除",g.getName()),Operation.oper_remove_group,js);
					
				}
				
			}
			//删除群组
			messageHelper.removeGroup(groupId);
		}
		
		
	}
	
	/**
	 * 作为成员被删除
	 * @param groupId
	 * @param userIds
	 * @param type
	 * @param imChannelContext
	 */
	public static  void removeUser(String groupId, User user) {
		ImServerConfig imServerConfig = ImConfig.Global.get();
		MessageHelper messageHelper = imServerConfig.getMessageHelper();
		Group g = RedisCacheManager.getCache(ImConst.GROUP).get(groupId+CommonKey.SUFFIX+ImConst.INFO , Group.class);
		if(!Objects.isNull(g) && user != null) {
			List<String> groups = RedisCacheManager.getCache(ImConst.USER).listGetAll(user.getUserId()+CommonKey.SUFFIX+ImConst.GROUP);
			//保证删除的人在组内
			if(groups.contains(groupId)) {
				//维护缓存关系
				messageHelper.removeGroupUser(user.getUserId(), groupId);
				//如果该用户在线，那么解绑有效，否则无效；保证用户可以在线时，可以交互
				JimServerAPI.unbindGroup(user.getUserId(), groupId);
				//删除群组的离线消息
				RedisCacheManager.getCache(ImConst.PUSH).remove(ImConst.GROUP+CommonKey.SUFFIX+groupId+CommonKey.SUFFIX+user.getUserId());
				
				JSONObject js = new JSONObject();
				//前端可能用得着
				js.put("groupId", groupId);
				//发送系统消息（此人不存在了,无须通知到个人）
				js.put("inUser", user.getUserId());
				SystemNotify.notifyGroup(
							g.getGroupId(), g.getName(), 
							String.format("%s已离开群,原因：被系统账户踢出", user.getNick()),SystemNotify.Operation.oper_exit_group,js);
				
			}
			
			
			
		}
		
		
	}
	
	/**
	 * 删除个人的离线消息
	 * @param userId
	 */
	public static void  removeOfflineMsg(String userId) {
		
		String key = ImConst.PUSH + CommonKey.SUFFIX + ImConst.USER;
		Set<String> msgKeys;
		try {
			msgKeys = JedisTemplate.me().keys(key);
			
			if(!CollectionUtils.isEmpty(msgKeys)){
				Iterator<String> iterator = msgKeys.iterator();
				while(iterator.hasNext()){
					//这里面是所有的离线消息
					String pushUserKey = iterator.next();
					//if包含了userId: 或者 : userId的 都去掉 （CommonKey.SUFFIX +  [userId 或者 fromUserId])
					if(pushUserKey.indexOf(CommonKey.SUFFIX + userId) > -1 ) {
						
						//ImConst.USER + CommonKey.SUFFIX + userId + CommonKey.SUFFIX + fromUserId
						pushUserKey  = pushUserKey.substring(pushUserKey.indexOf(ImConst.USER));
						//获取到所有离线消息 ，can Test
						//List<String> messageList = RedisCacheManager.getCache(ImConst.PUSH).sortSetGetAll(pushUserKey);
						//List<ChatBody> messageDataList = JsonKit.toArray(messageList, ChatBody.class);
						//删除所有Key
						RedisCacheManager.getCache(ImConst.PUSH).remove(pushUserKey);
						
					}
					
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
